<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <p>这是 html5 web worker 计数</p>
    <p>计数: <output id="result"></output></p>
    <button onclick="startWorker()">开始 Worker</button>
    <button onclick="stopWorker()">停止 Worker</button>
    <br />
    <script>
        var w;
        function startWorker() {
            if (typeof (Worker) !== "undefined") {
                if (typeof (w) == "undefined") {
                    // Worker 需要运行在服务器上
                    w = new Worker("js/demo_workers.js");
                }
                w.onmessage = function (event) {
                    document.getElementById("result").innerHTML = event.data;
                };
            }
            else {
                document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Workers...";
            }
        }

        function stopWorker() {
            w.terminate();
            // 复用 w 变量
            w = undefined;
        }
    </script>
</body>

</html>